<?php
namespace app\admin\controller;

use app\admin\model\AuthRule as AuthRuleModel;
use app\admin\AdminBase;
use think\Db;
use think\exception\ErrorException;
use think\facade\Validate;

/**
 * 后台菜单
 * Class Menu
 * @package app\admin\controller
 */
class Menu extends AdminBase
{

    protected $auth_rule_model;

    protected function initialize()
    {
        parent::initialize();
        $this->auth_rule_model = new AuthRuleModel();
    }

    /**
     * 后台菜单
     * @return mixed
     */
    public function index()
    {
        if ($this->request->isAjax()) {


                $admin_menu_list  = $this->auth_rule_model->
                fieldRaw("id,pid,title,name,status,sort,if(pattern=1,true,false) as isParent")->order('sort' ,'DESC')
                    ->order('id' ,'DESC')->select()->toArray();
                $admin_menu_level_list = array2tree($admin_menu_list);
                foreach ($admin_menu_level_list as &$vo){
                    if(isset($vo["children"])){
                        $children = $vo["children"];
                        $sort = array_column($children,'sort');
                        array_multisort($sort, SORT_DESC, $children);//排序处理
                        $vo["children"] = $children;
                    }

                    unset($vo);
                }


                return $this->layui_json($admin_menu_level_list,count($admin_menu_level_list));
        }


        return $this->fetch('index');


    }

    /**
     * 添加菜单
     * @param string $pid
     * @return mixed
     */
    public function create($pid = 0)
    {
        $admin_menu_list       = $this->auth_rule_model->order(['sort' => 'DESC', 'id' => 'ASC'])->select();
        $admin_menu_level_list = array2level($admin_menu_list);
        return $this->fetch('create', ['pid' => $pid,'admin_menu_level_list'=>$admin_menu_level_list]);
    }

    /**
     * 保存菜单
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $rule = [
                'pid'   => 'require',
                'title' => 'require',
                'name'  => function($value) {
                    if(!$value){
                        return '请输入规则';
                    }
                    $where = [['delete_time','=',Null],['name','=',$value]];
                    $count = $this->auth_rule_model->where($where)->count();

                    if($count){
                        return '规则已存在';
                    }
                    return true;
                },
                'sort'  => 'require|number'
            ];
            $msg = [
                'pid.require'   => '请选择上级菜单',
                'title.require' => '请输入菜单名称',
//                'name.require'  => '请输入规则',
//                'name.unique'  => '规则已存在',
                'sort.require'  => '请输入排序',
                'sort.number'   => '排序只能填写数字'
            ];
            $validate = Validate::rule($rule);
            $validate->message($msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError());
            }else {
                if ($this->auth_rule_model->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑菜单
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $admin_menu = $this->auth_rule_model->find($id);
        $admin_menu_list       = $this->auth_rule_model->order(['sort' => 'DESC', 'id' => 'ASC'])->select();
        $admin_menu_level_list = array2level($admin_menu_list);
        return $this->fetch('edit', ['admin_menu' => $admin_menu,'admin_menu_level_list'=>$admin_menu_level_list]);
    }

    /**
     * 更新菜单
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPut()) {

            $data            = $this->request->put();
            $data['id'] = $id;
            $rule = [
                'pid'   => 'require',
                'title' => 'require',
                'name'  => function($value,$data) {
                    if(!$value){
                        return '请输入规则';
                    }
                    $map = [];
                    $map[] = ['id','<>',$data['id']];
                    $map[] = ['name','=',$value];
                    $map[] = ['delete_time','=',Null];
                    $count = $this->auth_rule_model->where($map)->count();

                    if($count){
                        return '规则已存在';
                    }
                    return true;
                },
                'sort'  => 'require|number'
            ];

            $msg = [
                'pid.require'   => '请选择上级菜单',
                'title.require' => '请输入菜单名称',
//                'name.require'  => '请输入规则',
//                'name.unique'  => '规则已存在',
                'sort.require'  => '请输入排序',
                'sort.number'   => '排序只能填写数字'
            ];
            $validate = Validate::rule($rule);
            $validate->message($msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError());
            } else {
                if ($this->auth_rule_model->where("id",$id)->save($data) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除菜单
     * @param $id
     */
    public function delete($id)
    {
        $sub_menu = $this->auth_rule_model->where(['pid' => $id])->find();
        if (!empty($sub_menu)) {
            $this->error('此菜单下存在子菜单，不可删除');
        }
        if ($this->auth_rule_model->destroy($id)) {

            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}